//
//  JoUserViewController.m
//  RunningMan
//
//  Created by 姜勇利 on 16/5/19.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//

#import "JoUserViewController.h"
#import "masonry.h"
#import "JoInfoTableViewCell.h"
#import "JoUserEditViewController.h"
#import "JoLoginViewController.h"
#import "EMSDk.h"
#import "ELCImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <BmobSDK/Bmob.h>

@interface JoUserViewController ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate, ELCImagePickerControllerDelegate>

@property (nonatomic, strong) UITableView *infoTableView;

@property (nonatomic, strong) NSArray *arrTitle;

@property (nonatomic, strong) NSMutableArray *mArrInfo;

@property (nonatomic, strong) NSString *name;

@property (nonatomic, strong) NSString *autograph;

@property (nonatomic, strong) UIImagePickerController *pick;

@property (nonatomic, retain) UIImageView *imgHeader;

@property (nonatomic, retain) NSString *imgPath;

@property (nonatomic, strong) NSNumber *runID;

@property (nonatomic, strong) NSString *gender;

@end

@implementation JoUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"个人信息";
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.54 green:0.17 blue:0.88 alpha:1.0];
    [self creatSubViews];
    self.pick = [[UIImagePickerController alloc]init];
    _pick.delegate = self;
    _pick.allowsEditing = YES;
}

#pragma mark -
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    BmobQuery *query = [BmobQuery queryWithClassName:@"userInfo"];
    [query whereKey:@"userName" equalTo:[EMClient sharedClient].currentUsername];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
        for (BmobObject *obj in array) {
            self.name = [obj objectForKey:@"name"];
            NSNumber *sexNumber = [obj objectForKey:@"sex"];
            self.runID = [obj objectForKey:@"runID"];
            NSLog(@"-------------------------%@", _runID);
            self.autograph = [obj objectForKey:@"autogrph"];
            NSString *gender;
            if ([sexNumber isEqualToNumber:@1]) {
                gender = @"Male";
            }
            if ([sexNumber isEqualToNumber:@0]) {
                gender = @"Female";
            }
            if ([sexNumber isEqualToNumber:@3]) {
                gender = @"I don't Know";
            }
            if (self.area == nil) {
                self.area = @"未开启定位服务";
            }
            if (self.name == nil) {
                self.name = @"";
            }
            if (self.runID == nil) {
                self.runID = [NSNumber numberWithInteger:0];
            }
            if (self.gender == nil) {
                self.gender = @"I don't know";
            }
            self.mArrInfo = @[@"", [NSString stringWithFormat:@"%@", _runID], _name, gender, self.area, _autograph, @"",@"", @"", @""].mutableCopy;
            dispatch_async(dispatch_get_main_queue(), ^{
            [self.infoTableView reloadData];
            });
        }
        }
        if (error) {
            
        }
    }];

}

#pragma mark - 创建子控件
- (void)creatSubViews
{
    self.infoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.infoTableView];
    self.infoTableView.delegate = self;
    self.infoTableView.dataSource = self;
    [self.infoTableView registerClass:[JoInfoTableViewCell class] forCellReuseIdentifier:@"infoPool"];
    self.infoTableView.rowHeight = 44;
    self.arrTitle = @[@"头像", @"RunID", @"名字", @"性别", @"地区", @"个性签名", @"照片墙", @"", @"清除缓存", @"退出登录"];
    self.infoTableView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    self.infoTableView.separatorColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
}

// tableView协议˜方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrTitle.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JoInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"infoPool"];
    cell.textLabel.text = self.arrTitle[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.infoLabel.text = self.mArrInfo[indexPath.row];
    if (indexPath.row == 0) {
        self.imgHeader = [[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width *5 / 6.f - 40, 5, 60, 60)];
        _imgHeader.clipsToBounds = YES;
        _imgHeader.layer.cornerRadius = 30;
        [cell.contentView addSubview:_imgHeader];
        // 保存编辑结果
        NSUserDefaults *userDeaults = [NSUserDefaults standardUserDefaults];
        if ([userDeaults dataForKey:[EMClient sharedClient].currentUsername]) {
            [self.imgHeader setImage:[UIImage imageWithData:[userDeaults dataForKey:[EMClient sharedClient].currentUsername]]];
        }
        else
        {
            [self.imgHeader setImage:[UIImage imageNamed:@"1401835_shi04.jpg"]];
        }
    }
    if ([cell.textLabel.text isEqualToString:@""]) {
        cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if ([cell.textLabel.text isEqualToString:@"清除缓存"]) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if ([cell.textLabel.text isEqualToString:@"退出登录"]) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 70;
    }
    if (indexPath.row == 7) {
        return 18;
    }
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 选取头像
    if (indexPath.row == 0) {
        [self presentViewController:_pick animated:YES completion:^{
            
        }];
    }
// 编辑个人信息
    if (indexPath.row <= 5 && indexPath.row >= 1 && indexPath.row != 1 && indexPath.row != 4) {
        JoUserEditViewController *userEdit = [[JoUserEditViewController alloc]init];
        userEdit.number = indexPath.row;
        if (indexPath.row == 2) {
            userEdit.editText = _name;
        }
        if (indexPath.row == 5) {
            userEdit.editText = _autograph;
        }
        [self.navigationController pushViewController:userEdit animated:YES];
    }
// 照片墙照片选取
    if (indexPath.row == 6) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [alert addAction:[UIAlertAction actionWithTitle:@"选择照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePhoto];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"选择相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self localPhoto];
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
// 推出登录
    if (indexPath.row == 9) {
        NSLog(@"99999999999999");
        EMError *error = [[EMClient sharedClient] logout:YES];
        if (!error) {
            NSLog(@"退出成功");
            JoLoginViewController *loginPage = [[JoLoginViewController alloc]init];
            [self presentViewController:loginPage animated:YES completion:^{
                
            }];
        }
    }
    
}

#pragma mark - 
// 协议方法 保存编辑结果
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    if (img != nil) {
        self.imgHeader.image = img;
    }
    NSData *data;
    if (UIImagePNGRepresentation(img)) {
        data = UIImagePNGRepresentation(img);
    }
    else
    {
        data = UIImageJPEGRepresentation(img, 1.0);
    }
    [[NSFileManager defaultManager]createFileAtPath:self.imgPath contents:data attributes:nil];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:data forKey:[EMClient sharedClient].currentUsername];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    // 1. 获取编辑后的照片
    UIImage *image;
    switch (picker.sourceType) {
        case UIImagePickerControllerSourceTypeCamera:
            image = info[@"UIImagePickerControllerOriginalImage"];
            //将图片保存到相册
            [self saveImageToPhotos:image];
            break;
        case UIImagePickerControllerSourceTypePhotoLibrary:
            image = info[@"UIImagePickerControllerEditedImage"];
            break;
        default:
            break;
    }
    
    
    // 3. 关闭照片选择控制器
    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark - 
- (void)takePhoto
{
    // 照片来自相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    // 判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }
    else
    {
        UIAlertController *cameraAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"无法获取相机服务" preferredStyle:UIAlertControllerStyleAlert];
        [cameraAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [cameraAlert dismissViewControllerAnimated:YES completion:^{
                
            }];
        }]];
        [cameraAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:cameraAlert animated:YES completion:^{
            
        }];
    }
    
}

- (void)localPhoto
{
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc]init];
    // 选择图像最大数量为5，默认为4
    elcPicker.maximumImagesCount = 5;
    // elcPicker.returnsOriginalImage = YES; //只返回fullScreenImage,不是fullResolutionImage
    // elcPicker.returnsImage = YES; //如果是的 返回UIimage。如果没有,只返回资产位置信息
    // elcPicker.onOrder = YES; //对多个图像选择、显示和返回的顺序选择图像
    // elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //支持图片和电影类型
    elcPicker.imagePickerDelegate = self;
    [self presentViewController:elcPicker animated:YES completion:^{
        
    }];
}
// 协议方法
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    NSLog(@"实现ELCImagePickerController");
}

// 相册
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    NSMutableArray *array = [NSMutableArray array];
    [array removeAllObjects];
    [self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"%@", info);
    for (NSDictionary *dict in info) {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                //把图片取出来放到数组里面
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [array addObject:image];
            }
        
        }else {
            // NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
        }
    }
    
}
#pragma mark - 照片选择代理方法
//将图片保存到相册
- (void)saveImageToPhotos:(UIImage*)savedImage

{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

// 指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertController *saveAlert = [UIAlertController alertControllerWithTitle:@"保存提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:saveAlert animated:YES completion:^{
        
    }];
    [saveAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [saveAlert dismissViewControllerAnimated:YES completion:^{
            
        }];
    }]];
    [saveAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
